'use strict'
import React, {
    Component
} from 'react'
import {
    Link,
    hashHistory
} from 'react-router'

import Header from './Common/Header'
import Footer from './Common/Footer'
import ConfirmBox from './Common/ConfirmBox'
//import audioTest from '../audio/test3.wav'

import {
    HttpService,
    getLocalTime,
    Tips,
    viewerImg,
    getDefaultImg,
    phpUrl,
    browser,
    taskFinish,
    iosfocus,
    iosblur
} from '../Tools'

export default class TaskDetail extends Component {
    constructor(props) {
        super(props);
        this.config = {
            content: '确认删除该作业吗？'
        };
        this.replayShow = true;
        this.audioObj = null;
        this.vadiofile = null;
        this.isRead = true;
        this.state = {
            TaskDetail: [],
            replayList: [],
            replay: 0,
            show: 0,
            continueok: true,
            type: false,
            studentList1: [],
            studentList2: [],
            account1: 0,
            account2: 0,
            musicUrl: null,
            movieUrl: null
        }
    }
    componentWillMount() {
        HttpService.query({
            url: '/jxt-commonbackground/ajaxHomework.do',
            data: {
                homeworkId: this.props.params.id,
                jybTicket: sessionStorage.ticket,
                method: 'm105LoadHomeworkDetail'
            },
            async: false,
            success: (res => {
                if (res.code == 0) {
                    this.getReplay();
                    if (res.r.musicFiles || (res.r.attFilesUrl && res.r.attFilesUrl.split(',')[1].split('.')[1] == 'mp3')) {
                        let FileId = res.r.musicFiles || res.r.attFilesUrl.split('?')[1].split(',')[0].split('=')[1]
                        HttpService.query({
                            url: phpUrl + `/php/filedownload_url.php?FileId=${FileId}`,
                            success: (res => {
                                if (res.indexOf('fail') > -1) {
                                    Tips('未获取到语音文件')
                                } else {
                                    res = res.substring(res.indexOf('download'))
                                    this.setState({
                                        musicUrl: phpUrl + '/' + res
                                    })
                                }
                                console.log(res);
                            })
                        })
                    }
                    if (res.r.movieFiles) {
                        HttpService.query({
                            url: phpUrl + `/php/filedownload_url.php?FileId=${res.r.movieFiles}`,
                            success: (res => {
                                if (res.indexOf('fail') > -1) {
                                    Tips('未获取到视频文件')
                                } else {
                                    res = res.substring(res.indexOf('download'))
                                    this.setState({
                                        movieUrl: phpUrl + '/' + res
                                    })
                                }
                                console.log(res);
                            })
                        })
                    }
                    this.setState({
                        TaskDetail: res.r
                    });
                    this.replayShow = false;
                    if (sessionStorage.userrole != '家长') {
                        if (res.r.requireSign == 1)
                            this.isRead = false
                        this.getStudents(this.isRead, this.state.type);
                        this.getStudents(this.isRead, !this.state.type);
                    }
                    return;
                }
                Tips(res.msg, 0);
                this.setState({
                    continueok: false
                })
            })
        })
    }
    componentDidMount() {
        // this.audioObj = document.getElementById('audioObj');
        // this.vadiofile = document.getElementById('vadiofile');
    }

    //获取回复列表
    getReplay() {
        HttpService.query({
            url: '/jxt-commonbackground/ajaxHomework.do',
            data: {
                homeworkId: this.props.params.id,
                jybTicket: sessionStorage.ticket,
                method: 'm106LoadHomeworkReply'
            },
            success: (res => {
                if (res.code == 0) {
                    this.setState({
                        replayList: res.r.replys
                    });
                } else {
                    Tips(res.msg || '发生错误');
                }
            })
        })
    }

    //删除作业提示
    taskView() {
        this.setState({
            show: 1
        })
    }

    //关闭提示
    cfmCancel() {
        this.setState({
            show: 0
        })
    }

    //确认删除
    cfmSure() {
        this.setState({
            show: 0
        })
        HttpService.query({
            url: '/jxt-commonbackground/ajaxHomework.do',
            data: {
                homeworkId: this.props.params.id,
                jybTicket: sessionStorage.ticket,
                method: 'm203DeleteHomework'
            },
            success: (res => {
                if (res.code == 0) {
                    hashHistory.goBack(-1)
                } else {
                    Tips('删除作业失败');
                }
            })
        })
    }

    //回复显示
    replayView(replay) {
        if (replay == 0) {
            document.getElementById('replay').blur();
            document.getElementById('replay').value = '';
        } else {
            document.getElementById('replay').focus();
        }
        this.setState({
            replay
        })
    }

    //回复操作
    replayPublish(e) {
        e.preventDefault();
        const content = document.getElementById('replay').value;
        if (content == '') {
            Tips('请输入回复内容');
            return;
        }
        if (content.length > 50) {
            Tips('回复内容已超50字');
            return;
        }

        let data = {
            homeworkId: this.props.params.id,
            jybTicket: sessionStorage.ticket,
            method: 'm204AddReply',
            content
        };
        if (sessionStorage.userrole != '家长') {
            data.studentId = sessionStorage.userid
        }
        HttpService.query({
            url: '/jxt-commonbackground/ajaxHomework.do',
            data,
            success: (res => {
                if (res.code == 0) {
                    document.getElementById('replay').value = '';
                    document.getElementById('replay').blur();
                    this.setState({
                        replay: 0
                    })
                    Tips('回复成功');
                    this.getReplay();
                    if (sessionStorage.userrole == '家长') {
                        taskFinish('回复作业', (status, config) => {
                            if (status) {
                                this.config = config;
                                this.setState({
                                    sigle: 1,
                                    show: 1
                                })
                            }
                        })
                    }
                } else {
                    Tips('回复失败');
                }
            })
        })
    }
    //苹果手机样式问题
    replyContentFocus() {
        iosfocus()
    }
    replyContentBlur() {
        iosblur()
    }

    //附件预览
    linkDown() {
        const {
            id,
            attFilesUrl
        } = this.state.TaskDetail
        let link = ''
        if (sessionStorage.wherefrom == 'ios') {
            link = attFilesUrl.split(',')[0] + '&app=true&appdown=true&filename=' + encodeURIComponent(attFilesUrl.split(',')[1])
            location.href = link;
        } else {
            link = '/NtcDetailFile/' + id + '/' + encodeURIComponent(attFilesUrl.split(',')[1]) + '/' + encodeURIComponent(attFilesUrl.split(',')[0]);
            hashHistory.push(link);
        }
    }

    //视频播放
    videoPlay(movieFilesUrl) {
        if ($('#videofilebox').children().length > 0)
            return
        $('#videofilebox').html('<video src="' + this.state.movieUrl + '" controls="controls" autoplay="autoplay" />')
    }

    //音频播放暂停
    playPause() {
        this.audioObj = document.getElementById('audioObj');
        this.vadiofile = document.getElementById('vadiofile');
        if (this.vadiofile.paused) {
            this.vadiofile.play();
            this.audioObj.className = 'voiceting'
            this.vadiofile.loop = false;
            this.vadiofile.addEventListener('ended', function() {
                document.getElementById('audioObj').className = 'voicebo'
            }, false);
        } else {
            this.vadiofile.pause();
            this.audioObj.className = 'voicebo'
        }
    }

    //已读
    taskRead() {
        if (this.state.TaskDetail.sign == 1)
            return
        HttpService.query({
            url: '/jxt-commonbackground/ajaxHomework.do',
            data: {
                jybTicket: sessionStorage.ticket,
                method: 'signHomework',
                homeworkId: this.props.params.id
            },
            success: (res => {
                if (res.code == 0) {
                    let TaskDetail = this.state.TaskDetail
                    TaskDetail.sign = 1
                    this.setState({
                        TaskDetail
                    })
                } else {
                    Tips(res.msg, 0);
                }
            })
        })
    }
    //获取数据
    getStudents(isRead, type) {
        let method = ''
        if (isRead) {
            method = type ? 'listReadHomework' : 'listNotReadHomework'
        } else {
            method = type ? 'listSignHomework' : 'listNotSignHomework'
        }
        HttpService.query({
            //未读：listNotReadHomework
            //已读：listReadHomework
            //已签阅：listSignHomework
            //未签阅：listNotSignHomework
            url: '/jxt-commonbackground/ajaxHomework.do',
            data: {
                jybTicket: sessionStorage.ticket,
                method,
                homeworkId: this.props.params.id,
                page: 1,
                pagesize: 100
            },
            success: (res => {
                if (res.code == 0) {
                    const data = res.r.students,
                        len = data.length
                    if (len == 0)
                        return
                    if (type) {
                        this.setState({
                            account2: len,
                            studentList2: data
                        })
                    } else {
                        this.setState({
                            account1: len,
                            studentList1: data
                        })
                    }
                } else {
                    Tips(res.msg, 0);
                }
            })
        })
    }

    //设置已读未读或签阅未签约
    setType(type) {
        this.setState({
            type
        });
    }

    render() {
        const {
            courseName,
            title,
            remark,
            createTime,
            picFilesUrl,
            attFilesUrl,
            musicFilesUrl,
            movieFilesUrl,
            requireSign,
            sign,
            id
        } = this.state.TaskDetail
        const {
            show,
            sigle,
            replay,
            replayList,
            continueok,
            type,
            studentList1,
            studentList2,
            account1,
            account2,
            musicUrl
        } = this.state
        const repalyTagList = replayList.map((item, index) => {
            return (
                <li className="replay">
                    <img className="head" src={getDefaultImg()}/>
                    <a>{item.sendUserName}{item.sendUserType=='家长'?'的家长':'老师'} {/*getLocalTime(item.sendTime)*/}</a>
                    <p>{item.replyContent}</p>
                </li>
            )
        })

        const studentTags1 = studentList1.map((item, index) => {
            return (
                <li>{item.studentName}</li>
            )
        });
        const studentTags2 = studentList2.map((item, index) => {
            return (
                <li>{item.studentName}</li>
            )
        });

        return (
            <div className='hasfoot2'>
                <Header title='作业详情' link={sessionStorage.userrole != '家长'
                    ? <a className="h_link del" onClick={this.taskView.bind(this)}/>
                    : null}/>
                {continueok?<div className="pjb_noticelist pjb_ntcdetail">
                    <div className="pnt_item">
                        <h5>{courseName}：{title}</h5>
                        <div className="time">
                            {getLocalTime(createTime)}
                        </div>
                        <div className="intro">{remark}</div>
                    </div>
                    <div className="pnt_other">
                        <div>
                            {picFilesUrl || musicUrl||(attFilesUrl && attFilesUrl.indexOf(',')>-1)
                                ? <h5>附件</h5>
                                : ''}
                            <ul className="filelist">
                                {picFilesUrl
                                    ? <li className="nobj" >
                                            <img src={picFilesUrl} className="head-img" onClick={viewerImg.bind(this, 'data-src')} data-src={picFilesUrl}/>
                                            <img className="head" src={picFilesUrl}/>
                                            <a className='siglebar'>作业图片</a>
                                            {/*<p></p>*/}
                                        </li>
                                    : ''}
                                {musicUrl||(attFilesUrl&&attFilesUrl.split(',')[2].substring(1)=='mp3')
                                    ? <li className="voicebo relative" id='audioObj' onClick={this.playPause.bind(this)}>
                                            <a className='siglebar'>作业语音</a>
                                            <audio className='vadiofile' id='vadiofile' src={musicUrl}>不支持语音</audio>
                                        </li>
                                    : ''}
                                {attFilesUrl && attFilesUrl.indexOf(',')>-1 &&attFilesUrl.split(',')[2].substring(1)!='mp3'
                                    ? <li className={attFilesUrl.split(',')[2].substring(1)} onClick={this.linkDown.bind(this)}>
                                            <div>{attFilesUrl.split(',')[1]}</div>
                                            <p>{attFilesUrl.split(',')[3] + attFilesUrl.split(',')[4]}</p>
                                        </li>
                                    : ''}
                                    {
                                        movieFilesUrl?
                                        <li className='mp4' onClick={this.videoPlay.bind(this,movieFilesUrl)}>
                                            <div className='siglebar'>视频文件</div>
                                        </li>:null
                                    }

                            </ul>
                        </div>
                        <div id='videofilebox'></div>
                        {sessionStorage.userrole!='家长'?
                        <div className='growth_record_details_page' style={{minHeight:'auto',paddingBottom:0}}>
                            <div className="details_content">
                                <div className='type_list'>
                                    <div className={type == false? 'select': ''} onClick={this.setType.bind(this, false)}>{requireSign == 1?'未签阅':'未读'}({account1})</div>
                                    <div className={type == true? 'select': ''} onClick={this.setType.bind(this, true)}>{requireSign == 1?'已签阅':'已读'}({account2})</div>
                                </div>
                                <div className="student_list clearfix">
                                    <ul>
                                        {type == false?studentTags1:studentTags2}
                                    </ul>
                                </div>
                            </div>
                        </div>
                        :null}
                        {repalyTagList.length > 0
                            ? <h5>对话列表
                                </h5>
                            : ''}
                        <ul className="filelist">
                            {repalyTagList}
                        </ul>
                    </div>
                <Footer>
                    <a className={sessionStorage.userrole != '家长'|| requireSign == 0?'pjb_ntcread':'pjb_ntcread twosplit'} onClick={this.replayView.bind(this, 1)}>回复{sessionStorage.userrole != '家长'
                        ? '家长'
                        : '教师'}</a>
                    {sessionStorage.userrole == '家长' && requireSign == 1?<a className={sign==0?'pjb_ntcread twosplit2':'pjb_ntcread twosplit3'} onClick={this.taskRead.bind(this)}>我已阅读</a>:''}
                </Footer>
                </div>:''}
                <ConfirmBox config={this.config} show={show} cancel={this.cfmCancel.bind(this)} sigle={sigle} sure={this.cfmSure.bind(this)}/>
                <div className='iosinputbox' style={{display:this.replayShow==false?'block':'none',zIndex:replay == 1?'10':'-1',opacity:replay == 1?'1':'0'}}>
                    <div className='mask' onClick={this.replayView.bind(this, 0)} />
                    <div className='pjb_commentbox' >
                        <input type='text' ref='content' autoComplete='off' placeholder='输入回复内容（最多50字）' id="replay" onBlur={this.replyContentBlur.bind(this)} onFocus={this.replyContentFocus.bind(this)}/>
                        <input className='btn' type='button' value='发布' onClick={this.replayPublish.bind(this)} />
                    </div>
                </div>
            </div>
        )
    }
}
